<?php
session_start();
include 'configs/config.php';

$articles = [];
$message = isset($_GET['message']) ? htmlspecialchars($_GET['message']) : "";
$search_term = isset($_GET['search']) ? htmlspecialchars($_GET['search'], ENT_QUOTES, 'UTF-8') : "";

$is_admin = false; // 记录用户是否为管理员

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];

    // 检查用户等级
    $stmt = $conn->prepare("SELECT level FROM users WHERE id = ? LIMIT 1");
    if (!$stmt) {
        die('预处理语句准备失败: ' . $conn->error);
    }
    $stmt->bind_param("i", $user_id);
    if (!$stmt->execute()) {
        die('执行查询失败: ' . $stmt->error);
    }
    $stmt->bind_result($level);
    $stmt->fetch();
    $is_admin = $level == 1; // 如果 level 为 1，设置为管理员
    $stmt->close();
}

// 获取文章列表的函数
function getArticles($conn, $is_admin, $user_id, $search_term) {
    if ($is_admin) {
        if ($search_term) {
            $stmt = $conn->prepare("  
                SELECT a.id, a.title, a.body, a.time, u.username, a.user_id   
                FROM article a   
                JOIN users u ON a.user_id = u.id   
                WHERE a.title LIKE ? OR u.username LIKE ?
            ");
            $like_term = "%" . $search_term . "%";
            $stmt->bind_param("ss", $like_term, $like_term);
        } else {
            $stmt = $conn->prepare("  
                SELECT a.id, a.title, a.body, a.time, u.username, a.user_id   
                FROM article a   
                JOIN users u ON a.user_id = u.id   
            ");
        }
    } else {
        if (isset($user_id)) {
            if ($search_term) {
                $stmt = $conn->prepare("  
                    SELECT a.id, a.title, a.body, a.time, u.username, a.user_id   
                    FROM article a   
                    JOIN users u ON a.user_id = u.id   
                    WHERE (a.visibility = '公开' OR a.visibility = '部分公开' OR (a.visibility = '私密' AND a.user_id = ?))
                    AND (a.title LIKE ? OR u.username LIKE ?)  
                ");
                $like_term = "%" . $search_term . "%";
                $stmt->bind_param("iss", $user_id, $like_term, $like_term);
            } else {
                $stmt = $conn->prepare("  
                    SELECT a.id, a.title, a.body, a.time, u.username, a.user_id   
                    FROM article a   
                    JOIN users u ON a.user_id = u.id   
                    WHERE (a.visibility = '公开' OR a.visibility = '部分公开' OR (a.visibility = '私密' AND a.user_id = ?))
                ");
                $stmt->bind_param("i", $user_id);
            }
        } else {
            if ($search_term) {
                $stmt = $conn->prepare("  
                    SELECT a.id, a.title, a.body, a.time, u.username, a.user_id   
                    FROM article a   
                    JOIN users u ON a.user_id = u.id   
                    WHERE a.visibility = '公开'   
                    AND (a.title LIKE ? OR u.username LIKE ?)
                ");
                $like_term = "%" . $search_term . "%";
                $stmt->bind_param("ss", $like_term, $like_term);
            } else {
                $stmt = $conn->prepare("  
                    SELECT a.id, a.title, a.body, a.time, u.username, a.user_id   
                    FROM article a   
                    JOIN users u ON a.user_id = u.id   
                    WHERE a.visibility = '公开'  
                ");
            }
        }
    }

    if (!$stmt) {
        die('预处理语句准备失败: ' . $conn->error);
    }
    if (!$stmt->execute()) {
        die('执行查询失败: ' . $stmt->error);
    }
    $result = $stmt->get_result();
    $articles = [];
    while ($row = $result->fetch_assoc()) {
        $articles[] = $row;
    }
    $stmt->close();
    return $articles;
}

$articles = getArticles($conn, $is_admin, isset($user_id) ? $user_id : null, $search_term);
?>

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>查看文章</title>
    <link rel="stylesheet" href="static/articles.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
        }

        .container {
            width: 80%;
            margin: auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        li {
            margin-bottom: 15px;
            border-bottom: 1px solid #ddd;
            padding: 10px 0;
        }

        a {
            text-decoration: none;
            color: #0275d8;
        }

        a:hover {
            text-decoration: underline;
        }
    </style>
</head>

<body>
<div class="container">
    <div class="message"><?php echo $message; ?></div>

    <h2>文章列表</h2>
    <ul>
        <?php foreach ($articles as $article): ?>
            <li>
                <h3>
                    <a href="view_article.php?id=<?php echo $article['id']; ?>">
                        <?php echo htmlspecialchars($article['title']); ?>
                    </a>
                    (<?php echo htmlspecialchars($article['username']); ?>)
                </h3>
                <small>发表于: <?php echo htmlspecialchars($article['time']); ?></small>

                <?php if (isset($_SESSION['user_id'])): ?>
                    <?php if ($is_admin || $_SESSION['user_id'] == $article['user_id']): ?>
                        <form method="post" action="delete.php" class="delete-form">
                            <input type="hidden" name="article_id" value="<?php echo $article['id']; ?>">
                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                            <input type="submit" value="删除">
                        </form>
                        <a href="edit.php?id=<?php echo $article['id']; ?>">修改</a>
                    <?php endif; ?>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
</div>
</body>
</html>